/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfast.framework.web.core.param;

import com.jfast.framework.bean.ClassFactory;
import com.jfast.framework.bean.JdkClassFactory;
import com.jfast.framework.log.Logger;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

public abstract class RequestMappingMethodParam implements MethodParam {
	
	protected HttpServletRequest request;
	static final Logger logger = Logger.getLogger(RequestMappingMethodParam.class);
	static final ClassFactory classFactory = new JdkClassFactory();

	//是否json参数
	protected static boolean isJsonParams = false;

	public RequestMappingMethodParam(HttpServletRequest request){
		this.request = request;
	}

	protected void setJsonParams(boolean jsonParams) {
		isJsonParams = jsonParams;
	}

	@Override
	public Object getParam() {
		if (isJsonParams()) {
			String requestBody = readData();
			return doGetBeanByJson(requestBody);
		} else {
			Map<String, String[]> params = request.getParameterMap();
			return doGetBean(params);
		}
	}

	abstract Object doGetBean(Map<String, String[]> params);

	abstract Object doGetBeanByJson(String requestBody);

	/**
	 * 获取json 参数值
	 * @return
	 */
	public String readData() {
		BufferedReader br = null;
		try {
			StringBuilder ret;
			br = request.getReader();
			String line = br.readLine();
			if (line != null) {
				ret = new StringBuilder();
				ret.append(line);
			} else {
				return "";
			}
			while ((line = br.readLine()) != null) {
				ret.append('\n').append(line);
			}
			return ret.toString();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	protected boolean isJsonParams() {
		return isJsonParams;
	}
}
